package 线程;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程交替执行（不死等 等待别人唤醒）
 *
 * @author Administrator
 */
public class TestThread {
    static Integer index = 0;

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 3; i++) {
            final int num = i;
            pool.submit(() -> {
                while (true) {
                    Thread.sleep(200);
                    synchronized (pool) {
                        if (num == index) {
                            index = (index + 1) % 3;
                            System.out.println(num + 1);
                            pool.notifyAll();
                        } else {
                            pool.wait();
                        }
                    }
                }
            });
        }
    }
}
